package com.gitee.qdbp.jdbc.tags;

import java.io.IOException;
import com.gitee.qdbp.able.enums.WrapMode;
import com.gitee.qdbp.jdbc.api.SqlBoot;
import com.gitee.qdbp.jdbc.sql.SqlBuffer;
import com.gitee.qdbp.jdbc.sql.SqlTools;
import com.gitee.qdbp.staticize.annotation.OutputWrapper;
import com.gitee.qdbp.staticize.common.IWriter;
import com.gitee.qdbp.staticize.exception.TagException;
import com.gitee.qdbp.staticize.tags.base.NextStep;

/**
 * Include标签, 支持动态参数
 *
 * @author zhaohuihua
 * @version 140722
 * @since 3.2.0
 */
@OutputWrapper
public class IncludeTag extends SqlCachingTag {

    private final SqlBoot sqlBoot;
    private String refid;
    private String prefix;
    private String suffix;
    private String prefixOverrides;
    private String suffixOverrides;
    /** 是否添加括号 **/
    private WrapMode brackets;

    public IncludeTag(SqlBoot sqlBoot) {
        super(sqlBoot);
        this.sqlBoot = sqlBoot;
    }

    public void setRefid(String refid) {
        this.refid = refid;
    }

    protected String getPrefix() {
        return prefix;
    }

    protected void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    protected String getSuffix() {
        return suffix;
    }

    protected void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    protected String getPrefixOverrides() {
        return prefixOverrides;
    }

    protected void setPrefixOverrides(String prefixOverrides) {
        this.prefixOverrides = prefixOverrides;
    }

    protected String getSuffixOverrides() {
        return suffixOverrides;
    }

    protected void setSuffixOverrides(String suffixOverrides) {
        this.suffixOverrides = suffixOverrides;
    }

    protected WrapMode getBrackets() {
        return brackets;
    }

    protected void setBrackets(String brackets) {
        this.brackets = WrapMode.of(brackets, "brackets value");
    }

    /** {@inheritDoc} **/
    @Override
    public NextStep doHandle() throws TagException {
        return NextStep.EVAL_BODY;
    }

    @Override
    public final void doEnded(SqlBuffer buffer, IWriter writer) throws TagException, IOException {
        // 标签内不能包含SQL, 只能有<property>标签, 因此用不到buffer

        SqlBuffer sql = sqlBoot.sqlContainer().generate(refid, context().stack());
        if (sql.isBlank()) {
            return;
        }

        SqlTools.wrap(sql, brackets, prefix, prefixOverrides, suffix, suffixOverrides);
        String leadingBlank = clearLeadingBlank();
        if (leadingBlank != null) {
            sql.shortcut().pd(leadingBlank);
        }

        writer.write(sql);
    }
}
